import { useEffect } from "react";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import { Pagination } from "antd";
import { Card as SemiCard, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconRefresh } from "@douyinfe/semi-icons";

import { useApplication } from "../../hooks/application/organization";

import ApplicationTable from "../../components/application/organization/Table";

const AllOrganizationApplications = () => {
    const { windowInnerHeight } = useModel("global");
    const { appLoading, applications, totalCount, loadApplicationsByPage } = useApplication();

    const state = useReactive({
        page: 1,
        pageSize: 20,
    });

    const loadApplications = async () => {
        loadApplicationsByPage({
            order: [["aiName", "ASC"]],
            page: state.page,
            pageSize: state.pageSize,
        });
    };

    useEffect(() => {
        loadApplications();
    }, [state.page]);

    useEffect(() => {
        if (applications.length > 0) {
            state.selectedApplication = applications.find((item) => item.aiUuid === state.selectedApplication?.aiUuid);
            !state.selectedApplication && (state.selectedApplication = applications[0]);
        } else {
            state.selectedApplication = null;
        }
    }, [applications]);

    const SemiCardFooter = (
        <div style={{ padding: 6, textAlign: "center" }}>
            <Pagination
                total={totalCount}
                pageSize={state.pageSize}
                position={["none", "bottomCenter"]}
                hideOnSinglePage={false}
                showSizeChanger={false}
                onChange={(page) => (state.page = page)}
                itemRender={(_, type, originalElement) => {
                    if (type === "prev") return <a>上一页</a>;
                    if (type === "next") return <a>下一页</a>;
                    return originalElement;
                }}
            />
        </div>
    );

    const cardBodyHeight = windowInnerHeight - 90 - 54 - 20;

    return (
        <SemiCard
            title={<span style={{ lineHeight: "32px", fontSize: 16 }}>应用列表 ({totalCount})</span>}
            headerExtraContent={
                <ButtonGroup>
                    <Button icon={<IconRefresh />} onClick={loadApplications}></Button>
                </ButtonGroup>
            }
            headerStyle={{ padding: "10px 14px" }}
            shadows="always"
            bordered={false}
            bodyStyle={{ padding: 0, height: cardBodyHeight - 46 }}
            footerStyle={{ padding: 0 }}
            footerLine={true}
            footer={SemiCardFooter}
            style={{ margin: 10 }}
        >
            <ApplicationTable appLoading={appLoading} applications={applications} reloadData={loadApplications} cardBodyHeight={cardBodyHeight} />
        </SemiCard>
    );
};

export default AllOrganizationApplications;
